package com.oak.broke.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * websocket请求拦截器
 *
 * @Author xyguo22
 * @Description //TODO
 * @Date 2024/7/24
 */
@Slf4j
public class RagHandshakeInterceptor implements HandshakeInterceptor {


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        log.info("ws连接握手前准备");
        // 在基于Servlet的环境中，可以将ServerHttpRequest转换为HttpServletRequest
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            HttpSession session = servletRequest.getSession(); // 不创建新会话

            if (session != null) {
                // 设置用户信息
                //final UapUser sessionUser = (UapUser) session.getAttribute(Constant.SESSION_USER);
                //if (sessionUser != null) {
                    //attributes.put(WebSocketConstants.USER_INFO, sessionUser);
                    //log.info("设置ws连接当前用户信息：id={},loginName={}",sessionUser.getId(),sessionUser.getLoginName());
                //}
            }
        }
        return true; // 如果返回false，则握手过程将被终止
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {
        // 握手后的处理（可选）
    }
}
